// 兼容ie9+
import httpUtil from './httpUtil'
import axios from 'axios/index'
import validateUtil from './validateUtil'
import commonUtil from './commonUtil'
import dialogUtil from './dialogUtil'
import config from '../config/config'

require('es6-promise').polyfill()

axios.defaults.timeout = config.axiousConfig.timeout // 设置响应时间
axios.defaults.baseURL = config.rootConfig.apiRootPath // API地址
axios.defaults.withCredentials = config.axiousConfig.withCredentials // 不需要信任
axios.defaults.crossDomain = config.axiousConfig.crossDomain // 跨域

//代理
axios.defaults.baseURL = process.env.NODE_ENV !== "production" ? "" : ""

export default class axiosUtil {
  // 上传(需要验证)
  static upload(url, fileData, callback) {
    const instance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    const configs = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    } // 添加请求头
    instance.defaults.headers.post['Content-Type'] = 'multipart/form-data'
    httpUtil.authorityUnifyHandle(instance)
    instance.post(url, fileData, configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // TODO:OK
  static uploadNo(url, fileData, callback) {
    const instance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    const configs = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    } // 添加请求头
    instance.defaults.headers.post['Content-Type'] = 'multipart/form-data'
    instance.post(url, fileData, configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // TODO:OK
  static postJson(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {};
    }
    data = httpUtil.handleData(data, config.commonParameter)
    const postJsonInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    postJsonInstance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      }
    } // 添加请求头
    httpUtil.authorityUnifyHandle(postJsonInstance);
    console.log(data, "********************")
    postJsonInstance.post(url, JSON.stringify(data), configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };
  // TODO:新增
  static postAddJson(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {};
    }
    data = httpUtil.handleData(data, config.commonParameter)
    const postJsonInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    postJsonInstance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      }
    } // 添加请求头
    httpUtil.authorityUnifyHandle(postJsonInstance);
    postJsonInstance.post(url, JSON.stringify(data), configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };
  // TODO:编辑
  static postUpdateJson(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {};
    }
    data = httpUtil.handleData(data, config.commonParameter)
    const postJsonInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    postJsonInstance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      }
    } // 添加请求头
    httpUtil.authorityUnifyHandle(postJsonInstance);
    postJsonInstance.post(url, JSON.stringify(data), configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // TODO:OK
  static postJsonNo(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {}
    }
    // data = httpUtil.handleData(data, config.commonParameter)
    const postJsonNoInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    postJsonNoInstance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      }
    } // 添加请求头
    postJsonNoInstance.post(url, JSON.stringify(data), configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // TODO:OK
  static post(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {}
    }
    data = httpUtil.handleData(data, config.commonParameter)
    data = httpUtil.requestDataUnifyHandle(data)
    const postInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    postInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    } // 添加请求头
    httpUtil.authorityUnifyHandle(postInstance);
    httpUtil.requestUnifyHandle(postInstance)
    return postInstance.post(url, data, configs).then(response => {
      callback(httpUtil.responseUnifyHandleByJson(response))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // TODO:OK
  static postStatics(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {}
    }
    data = httpUtil.handleData(data, config.commonParameter)
    data = httpUtil.requestDataUnifyHandle(data)
    const postInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    postInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    } // 添加请求头
    httpUtil.authorityUnifyHandle(postInstance)
    httpUtil.requestUnifyHandle(postInstance)
    return postInstance.post(url, data, configs).then(response => {
      callback(httpUtil.responseUnifyHandleByStatics(response))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // TODO:OK
  static postNo(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {}
    }
    data = httpUtil.handleData(data, config.commonParameter)
    data = httpUtil.requestDataUnifyHandle(data)
    const postNoInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    postNoInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    } // 添加请求头
    httpUtil.requestUnifyHandle(postNoInstance)
    return postNoInstance.post(url, data, configs).then(response => {
      callback(httpUtil.responseUnifyHandleByJson(response))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  static getUrl(url, callbakc) {
    const getInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    getInstance.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }
    return getInstance.get(url, configs).then(response => {
      callback(response)
    }).catch(err => {
      console.log(err)
    })
  }

  // TODO:OK
  static get(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {}
    }
    if (validateUtil.isNotNull(data)) {
      let paramStr = ''
      for (const key in data) {
        paramStr += key + '=' + data[key] + '&'
      }
      if (paramStr.length > 0) {
        paramStr = paramStr.substr(0, paramStr.length - 1)
      }
      url = url + '?' + paramStr
    }
    const getInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    getInstance.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }
    httpUtil.authorityUnifyHandleByGet(getInstance)
    httpUtil.requestUnifyHandle(getInstance)
    return getInstance.get(url, configs).then(response => {
      callback(httpUtil.responseUnifyHandleByJson(response))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // TODO:OK
  static getNO(url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data = {}
    }
    data = httpUtil.requestDataUnifyHandle(data)
    const getNoInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    getNoInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    httpUtil.requestUnifyHandle(getNoInstance)
    return getNoInstance.get(url, data).then(response => {
      callback(httpUtil.responseUnifyHandleByJson(response))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };

  // ODO:OK
  static postHtml(url, fileName, data) {
    if (validateUtil.isNull(data)) {
      data = {}
    }
    const token = config.constantConfig.userTokenConstant
    // const authorParam = storeUtil.getAuthority()
    axios({
      method: 'post',
      url: url,
      data: data,
      responseType: 'blob'
    }).then((res) => { // 处理返回的文件流

      const content = res
      const blob = new Blob([content])
      commonUtil.downLoadClick(blob, fileName)
    })
  }
   // TODO:新增
   static postAddJson (url, data, callback) {
   
    if (validateUtil.isFunction(data)) {
      callback = data
      data ={};
    }
    
    if(data.constructor===Array){
      data.forEach((item)=>{
        item.creator=JSON.parse(window.sessionStorage.getItem('authorityList')).overallUserID
      })
    }
    if(data.constructor===Object){
      
      function abc(data){
        if(typeof data == "object"){
          data.creator=JSON.parse(window.sessionStorage.getItem('authorityList')).overallUserID
          
          for( var key in data){
            
            if(data[key]&&typeof data[key] == "object"){
              
              
              
              data[key].creator=JSON.parse(window.sessionStorage.getItem('authorityList')).overallUserID
              abc(data[key])
            }
          }
        }
        
      }
      abc(data)
  
    }
    
    
    
    data=httpUtil.handleData(data,config.commonParameter)
    data.loading=true
    const postJsonInstance = axios.create({ withCredentials: config.axiousConfig.withCredentials, crossDomain: config.axiousConfig.crossDomain })
    postJsonInstance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    const configs = { headers: { 'content-type': 'application/json;charset=UTF-8','osTenantId':'3ad8bce569694baabe8ee82555ee23ee' } } // 添加请求头
    httpUtil.authorityUnifyHandle(postJsonInstance);
    postJsonInstance.post(url, JSON.stringify(data), configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };
  // TODO:编辑
  static postUpdateJson (url, data, callback) {
    if (validateUtil.isFunction(data)) {
      callback = data
      data ={};
    }
    if(data.constructor===Array){
      data.forEach((item)=>{
        item.updater=JSON.parse(window.sessionStorage.getItem('authorityList')).overallUserID
      })
    }
    if(data.constructor===Object){
      
      function abc(data){
        if(typeof data == "object"){
          data.updater=JSON.parse(window.sessionStorage.getItem('authorityList')).overallUserID
          
          for( var key in data){
            
            if(typeof data[key] == "object"){
              data[key].updater=JSON.parse(window.sessionStorage.getItem('authorityList')).overallUserID
              abc(data[key])
            }
          }
        }
        
      }
      abc(data)
  
    }
    data=httpUtil.handleData(data,config.commonParameter)
    data.loading=true
    const postJsonInstance = axios.create({ withCredentials: config.axiousConfig.withCredentials, crossDomain: config.axiousConfig.crossDomain })
    postJsonInstance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    const configs = { headers: { 'content-type': 'application/json;charset=UTF-8','osTenantId':'3ad8bce569694baabe8ee82555ee23ee' } } // 添加请求头
    httpUtil.authorityUnifyHandle(postJsonInstance);
    postJsonInstance.post(url, JSON.stringify(data), configs).then(res => {
      callback(httpUtil.responseUnifyHandleByJson(res))
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };
  // TODOS:需要修改
  static getFile(url, downloadFileName) {
    const responseType = {
      responseType: 'blob'
    }
    const fileInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    // 设置头
    fileInstance.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Access-Control-Allow-Origin': '*'
      },
      responseType: 'blob'
    } // 添加请求头
    httpUtil.authorityUnifyHandleByGet(fileInstance)
    // httpUtil.authorityUnifyHandle(fileInstance);
    return fileInstance.get(url, configs).then(res => {
      if (res && res.status === 200 && res.data) {
        const content = res.data
        const blob = new Blob([content])
        commonUtil.downLoadClick(blob, downloadFileName)
      } else {
        dialogUtil.errorMsg(res)
      }
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };
  //文件下载
  static getFileByPost(url, callback) {
    const responseType = {
      responseType: 'blob'
    }
    const fileInstance = axios.create({
      withCredentials: config.axiousConfig.withCredentials,
      crossDomain: config.axiousConfig.crossDomain
    })
    // 设置头
    fileInstance.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    const configs = {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Access-Control-Allow-Origin': '*'
      },
      loading: true,
      responseType: 'blob'
    } // 添加请求头
    httpUtil.authorityUnifyHandleByGet(fileInstance)
    // httpUtil.authorityUnifyHandle(fileInstance);
    return fileInstance.post(url, {
      ...responseType
    }, configs).then(res => {
      if (res && res.status === 200 && res.data) {
        const content = res.data
        callback(res);
      } else {
        dialogUtil.errorMsg(res)
      }
    }).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  };
  /* ---------------- */
  static postImgPreview(url, data, callback) {
    if (validateUtil.isNull(data)) { data = {} }
    const token = config.constantConfig.userTokenConstant
    // const authorParam = storeUtil.getAuthority()
    const fileInstance = axios.create({ withCredentials: config.axiousConfig.withCredentials, crossDomain: config.axiousConfig.crossDomain })
    axios({ method: 'post', url: url, responseType: 'blob' }).then((res) => { // 处理返回的文件流
      callback(res);
    })
  }

  /* ************** */
  //模拟接口
  static mockData(url, config) {
    const request = axios.create({})
    return request({
      url,
      method: (config && config.method) || "GET"
    })
  }

  //api 代理请求
  static interfaceProxy(data) {
    let request = axios.create({
      baseURL: '/api2'
    })
    return request(data).then(({
      data
    }) => data).catch(err => {
      return httpUtil.errorUnifyHandle(err)
    })
  }
  //上传
}